import { ApiResponse, User, UserProfile } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import request from '@/utils/request'

//获取用户自己信息
export const getProfile = (): RootThunkAction => {
  return async (dispath) => {
    const res = await request.get<ApiResponse<User>>('/user')
    // console.log(res)
    console.log(res.data.data)
    dispath({
      type: 'profile/getProfile',
      payload: res.data.data,
    })
  }
}

//获取用户个人资料
export const getUserProfile = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<UserProfile>>('/user/profile')
    console.log(res)
    dispatch({
      type: 'profile/getUserProfile',
      payload: res.data.data,
    })
  }
}
//修改个人信息 /user/profile
export const updateUserProfile = (
  key: string,
  value: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.patch('/user/profile', {
      [key]: value,
    })
    console.log(res)
    //立刻获取 重新渲染
    await dispatch(getUserProfile())
  }
}

//修改头像
export const updatePhoto = (fd: FormData): RootThunkAction => {
  return async (dispatch) => {
    await request.patch('/user/photo', fd)
    dispatch(getUserProfile())
  }
}
